<template>
  <n-modal v-model:show="isVisible" title="编辑采购计划" preset="dialog" @close="onClose" @update:show="onClose"
           style="height: 420px;width: 700px">
    <n-form @submit.prevent="handleSubmit" label-width="120px" class="form-container">
      <div class="form-row" style="margin-top: 20px">
        <n-form-item label="采购产品：" path="productId">
          <n-select v-model:value="form.productId"
                    placeholder="请选择产品"
                    :options="products"
                    style="width: 190px"
                    disabled
                    @update:value="handleProductChange"
          ></n-select>
        </n-form-item>
        <n-form-item label="采购数量：" path="quantity" style="margin-left: 20px">
          <n-input v-model:value="form.quantity" placeholder="请输入采购数量" style="width: 190px" disabled/>
        </n-form-item>
        <n-form-item label="入库仓库：" path="quantity" style="margin-left: 20px">
          <n-select
              v-model:value="form.storeId"
              :options="stores"
              style="width: 190px"
              clearable
              disabled
          ></n-select>
        </n-form-item>
      </div>

      <div class="form-row">
        <n-form-item label="计划金额：" path="price">
          <n-input v-model:value="form.price" placeholder="请输入计划金额" style="width: 190px" disabled/>
        </n-form-item>
        <n-form-item label="计划时间：" path="time" style="margin-left: 20px">
          <n-date-picker
              v-model:formatted-value="time"
              placeholder="请选择计划时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              style="width: 190px"
              disabled/>
        </n-form-item>
        <n-form-item label="计划负责人：" path="adminId" style="margin-left: 20px">
          <n-select
              v-model:value="form.adminId"
              style="width: 190px"
              disabled
              :options="admins"></n-select>
        </n-form-item>
      </div>

      <div class="form-row" style="margin-top: 20px">
        <n-form-item label="供应商：" path="supplierId">
          <n-select v-model:value="form.supplierId"
                    placeholder="请选择供应商"
                    :options="suppliers"
                    style="width: 190px"
          ></n-select>
        </n-form-item>
        <n-form-item label="采购联系人：" path="contactPersonId" style="margin-left: 20px">
          <n-select
              v-model:value="form.contactPersonId"
              :options="contactPersons"
              style="width: 190px"
              clearable
          ></n-select>
        </n-form-item>
        <n-form-item label="联系电话：" path="contactPhone" style="margin-left: 20px">
          <n-input v-model:value="form.contactPhone" placeholder="请输入联系电话" style="width: 190px"/>
        </n-form-item>
      </div>

      <!-- 提交按钮 -->
      <div class="submit-row">
        <n-form-item>
          <n-button type="primary" native-type="submit" @click="handleSubmit">批准</n-button>
        </n-form-item>
        <n-form-item>
          <n-button type="error" native-type="submit" @click="handleReject" style="margin-left: 20px">驳回</n-button>
        </n-form-item>
      </div>
    </n-form>
  </n-modal>
</template>

<script setup>

import {onMounted, ref, watch} from 'vue';
import {useRouter} from 'vue-router';
import {useUserStore} from "@/store/index.js";
import api from '@/api/admin'
import {List} from "echarts";
import { NIcon } from 'naive-ui';

const loading = ref(true)
const userStore = useUserStore()
const id = userStore.getId();
const router = useRouter()
const products = ref([])
const stores = ref([])
const suppliers = ref([])
const admins = ref([])
const contactPersons = ref([])
const emit = defineEmits(['updatePage'])
const props = defineProps({
  show1: {
    type: Boolean,
    required: true,
  },
  onClose: {
    type: Function,
    required: true,
  },
  option: {
    type: List,
    require: true
  },
  attribute: {
    type: Object,
    required: true,
  }
});
const statusOptions = ref([
  {
    label: '未通过',
    value: '未通过',
  },
  {
    label: '未进行',
    value: '未进行',
  },
  {
    label: '进行中',
    value: '进行中',
  },
  {
    label: '已完成',
    value: '已完成',
  }
])

const time = ref(null)

const isVisible = ref(props.show1);
watch(() => props.show1, (newVal) => {
  isVisible.value = newVal;
  if (newVal) {
    // 当对话框显示时，将传递过来的属性值填充到表单中
    form.value = {...props.attribute};
		delete form.value.id
    time.value = props.attribute.planTime;
  }
});

const form = ref({
  productId: '',
  storeId: '',
  adminId: '',
  adminId1: '',
  quantity: '',
  price: '',
  status: '',
  planTime: '',
  contactPersonId: ''
});

const handleSubmit = async () => {
	console.log("form:")
	console.log(form.value)
  try {
    const res = await api.addPurchaseOrder(
        {
          ...form.value,
          id:"",
          adminId: form.value.contactPersonId,
          status: "待采购"
        }
    )
    const res1 = await api.updatePurchasePlan(
        {
          ...form.value,
          adminId: form.value.adminId,
          status: "批准",
          id:props.attribute.id
        }
    )
    if (res.code === 200 && res1.code === 200) {
      emit("updatePage")
      $message.success("批准成功！")
    } else {
      $message.error(res.message)
      $message.error(res1.message)
    }
  } catch (err) {
    $message.error("审批采购计划失败！")
  } finally {
    clear()
    props.onClose();
  }
};

const handleReject = async () => {
  try {
    const res = await api.updatePurchasePlan(
        {
          ...form.value,
          adminId: form.value.adminId,
          status: "驳回",
          id:props.attribute.id
        }
    )
    if (res.code === 200) {
      emit("updatePage")
      $message.success("驳回成功！")
    } else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("驳回采购计划失败！")
  } finally {
    clear()
    props.onClose();
  }
};
const queryAdminList = async () => {
  loading.value = true
  try {
    const res = await api.findAdminByRole({
      role: 'PURCHASEADMIN'
    })
    if (res.code === 200) {
      res.data.map((item) => {
        admins.value.push({
          label: item.name,
          value: item.id
        })
        contactPersons.value.push({
          label: item.name,
          value: item.id
        })
      })
    } else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取管理员信息失败！")
  } finally {
    loading.value = false
  }
}
const querySupplierList = async () => {
  loading.value = true
  try {
    const res = await api.findAllSupplier()
    if (res.code === 200) {
      res.data.map((item) => {
        suppliers.value.push({
          label: item.name,
          value: item.id
        })
      })
    } else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取供应商信息失败！")
  } finally {
    loading.value = false
  }
}
const queryStoreList = async () => {
  loading.value = true
  try {
    const res = await api.findAllStore()
    if (res.code === 200) {
      res.data.map((item) => {
        stores.value.push({
          label: item.name,
          value: item.id
        })
      })
    } else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取仓库信息失败！")
  } finally {
    loading.value = false
  }
}
const queryProductList = async () => {
  loading.value = true
  try {
    const res = await api.findAllProduct()
    if (res.code === 200) {
      res.data.map((item) => {
        products.value.push({
          label: item.name,
          value: item.id
        })
      })
    } else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("获取产品信息失败！")
  } finally {
    loading.value = false
  }
}
const clear = () => {
  form.value.productId = null
  form.value.storeId = null
  form.value.adminId = null
  form.value.quantity = ""
  form.value.price = ""
  form.value.status = ""
  time.value = null

}
onMounted(() => {
  queryStoreList()
  queryAdminList()
  queryProductList()
  querySupplierList()
})
</script>
<style scoped>
.form-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  position: relative;
}

.form-row {
  display: flex;
  align-items: center;
  width: 100%;
}

.form-row > n-form-item {
  flex: 1;
}

.submit-row {
  justify-content: center;
  display: flex;
  width: 100%;
}
</style>
